package com.demo.controller;

import com.demo.model.Board;
import com.demo.model.Card;
import com.demo.view.CardsView;
import com.demo.view.GameWindow;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

public class BackWardListener implements ActionListener {

    private static final BackWardListener instance = new BackWardListener();

    private List<Card> prevCards;
    private int[][] prevGrid;
    private int prevScore;

    private BackWardListener() {
    }

    /**
     * 撤回前一步
     */
    public void back() {
        if (prevCards == null || prevGrid == null) {
            return;
        }
        Board.getInstance()
                .setGrid(prevGrid)
                .setCards(prevCards)
                .setScore(prevScore);
        clear();
        CardsView.getInstance().repaint();
    }

    /**
     * 为撤回进行准备
     */
    public void prepareToBack() {
        Board board = Board.getInstance();
        prevCards = CardsHandler.copyCards(board.getCards());
        prevGrid = CardsHandler.copyGrid(board.getGrid());
        prevScore = board.getScore();
    }

    public void clear() {
        prevGrid = null;
        prevCards = null;
        prevScore = -1;
    }

    public static BackWardListener getInstance() {
        return instance;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        MoveCardListener moveListener = MoveCardListener.getInstance();
        if (moveListener.isAvailable()) {
            back();
        }
        // 让游戏窗口重获焦点（否则键盘无法操作）
        GameWindow.getInstance().requestFocus();
    }
}
